#!/usr/bin/env python
# -*- coding: utf-8 -*- 
'''
Run by python2.7+,not python3.0+
首次账号密码登录后,保存cookie文件,用于以后访问验证
'''
from subprocess import Popen,PIPE,check_output
import requests,configparser,re
import urllib,urllib2,cookielib,os,sys
import pickle
import json
###[hostname message]#####
def get_HostnameInfo(file):
    with open(file,'r') as fd:
        data = fd.read().split('\n')
        hostname = data[0]
    return hostname
#####[ipaddr message]#####
def get_Ipaddr():
    Manufacturer,product,sn = get_dmidecode()
    if 'ECS' in product:
        data = check_output(["curl -s cip.cc |awk -F':' '/IP/{print $2}'|sed 's/^[ \t]*//g'"],shell=True)
    else:
        data = check_output(["ifconfig | egrep 'inet6? ' | sed 's#addr: #addr:#g' | awk '{print $2}' | sed -E 's#addr:##g'|grep -Ev '127.0.0.1|*.0.1'|head -1"],shell=True)
    data = str(data).lstrip('b')
    data = data.strip('\n')
    return data
#####[osversion message]#####
def get_OsVerion(file):
    with open(file) as fd:
        lines = fd.readlines()
        os_version = lines[0][:-8] if file == '/etc/centos-release' else lines[-1].split('"')[1]
    return os_version
#####[memory message]#####
def get_MemoryInfo(file):
    with open(file) as fd:
        data_list = fd.read().split('\n')
        MemTotal_line = data_list[0]
        Memory_K = MemTotal_line.split()[1]
        Memory_G = float(Memory_K)/1000/1000
        Memory_G2 = '%.2f' % Memory_G
        memory = Memory_G2 + 'G'
    return memory
#####[disk message]#####
def get_DiskInfo():
    p = Popen(['fdisk','-l'],stdout=PIPE,stderr=PIPE)
    stdout,stderr = p.communicate()
    diskdata = stdout
    disk_initial_size = 0
    re_disk_type = re.compile(r'Disk /dev/[sihvd]{1}.*:\s+[\d.\s\w]*,\s+([\d]+).*')
    disk_size_bytes = re_disk_type.findall(diskdata)
    for size in disk_size_bytes:
        disk_initial_size += int(size)
        disk_size_total_bytes = '%.2f' % (float(disk_initial_size)/1000/1000/1000)
        disk_size_total_G = disk_size_total_bytes + 'G'
        disk = disk_size_total_G
    return disk
#####[cpu message]#####
def get_CpuInfo():
    p = Popen(['cat','/proc/cpuinfo'],stdout=PIPE,stderr=PIPE)
    stdout, stderr = p.communicate()
    cpudata = stdout.strip()
    cpu_dict = {}
    re_cpu_cores = re.compile(r'processor\s+:\s+([\d])')
    re_vendor_id = re.compile(r'vendor_id\s+:\s([\w]+)')
    re_model_name = re.compile(r'model name\s+:\s+(.*)')
    res_cpu_cores = re_cpu_cores.findall(cpudata)
    cpu_dict['Cpu_Cores'] = int(res_cpu_cores[-1]) + 1
    res_vendor_id = re_vendor_id.findall(cpudata)
    cpu_dict['Vendor_Id'] = res_vendor_id[-1]
    res_model_name = re_model_name.findall(cpudata)
    cpu_dict['Model_Name'] = res_model_name[-1]
    return cpu_dict
#####[Demi message]#####
def get_dmidecode():
    P = Popen(['dmidecode'],stdout=PIPE)
    data = P.stdout.read()
    lines = data.split('\n\n')
    dmidecode_line = lines[2]
    line = [i.strip() for i in dmidecode_line.split('\n') if i]
    Manufacturer = line[2].split(': ')[-1]
    product = line[3].split(': ')[-1]
    sn = line[5].split(': ')[-1]
    return Manufacturer,product,sn
def login(URL):
    data={"username":user,"password":pwd}  #登陆用户名和密码
    post_data=urllib.urlencode(data)   #将post消息化成可以让服务器编码的方式
    ckjar = cookielib.MozillaCookieJar('/tmp/.cookie')
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(ckjar))
    #自己设置User-Agent（可用于伪造获取，防止某些网站防ip注入）
    headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
    website = "%s/accounts/login/?next=/hostinfo/" % URL
    req=urllib2.Request(website,post_data,headers)
    content=opener.open(req)
    htm = content.read()
    content.close
    ckjar.save(ignore_discard=True, ignore_expires=True)
def requests_status(URL):
    try:
        conn = requests.get(URL)
        if conn.status_code not in range(200,400):
            print ("站点:%s 不可用或不可达!") % URL
            return 1
        else:
            #print ("HTTP_CODE:%s") % conn.status_code
            return 0
    except:
        print ("站点:%s 不可用或不可达!") % URL
        return 1
if __name__ == '__main__':
#####[get data]#####
    hostname = get_HostnameInfo('/etc/hostname')
    ip = get_Ipaddr()
    osversion = get_OsVerion('/etc/lsb-release') if os.path.isfile('/etc/lsb-release') else get_OsVerion('/etc/centos-release')
    memory = get_MemoryInfo('/proc/meminfo')
    disk = get_DiskInfo()
    Vendor_Id = get_CpuInfo()['Vendor_Id']
    Model_Name = get_CpuInfo()['Model_Name']
    Cpu_Cores = get_CpuInfo()['Cpu_Cores']
    Manufacturer,product,sn = get_dmidecode()
#####[get dict]#####
    hostinfo = {
     'hostname':hostname,
     'ip':ip,
     'osversion':osversion,
     'memory':memory,
     'disk':disk,
     'vendor_id':Vendor_Id,
     'model_name':Model_Name,
     'cpu_core':Cpu_Cores,
     'product':product,
     'Manufacturer':Manufacturer,
     'sn':sn,
}
    cf = configparser.RawConfigParser()
    domain = ''
    current_dir = os.path.dirname(__file__)
    config = "%s/url.conf" % current_dir
    if os.path.exists(config):
        cf.read(config)
    else:
        print ('不存在url.conf配置文件!')
        os._exit(1)
    url = cf.get(r"url","address")
    port = cf.get(r"url","port")
    user = cf.get(r"url","user")
    pwd = cf.get(r"url","password")	
    if not re.search("[<http://>|<https://>]",url):
        print ("配置文件:\'%s\'中url参数:\'%s\'前必须添加\'[http|https]://\'!") % (config,url)
        os._exit(1)
    elif re.search("[<http://>|<https://>]",url) and port == '':
        domain=url
    elif url and port:
        domain=url if port == '80' or port == '443' else url+":"+port
    else:
        print ('url.conf文件参数配置不能为空,请检查参数!')
        os._exit(1)
    cookie=cookielib.MozillaCookieJar()
    if not os.path.exists('/tmp/.cookie'): 
    #save token
        code=requests_status(domain)
        if code == 0:
            login(domain)
    cookie.load('/tmp/.cookie',ignore_expires=True,ignore_discard=True)
    # post data by token
    if requests_status(domain) == 0:
        req=urllib2.Request("%s/hostinfo/" % domain)
        opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        urllib2.install_opener(opener)
        #print hostinfo
        #data = urllib.urlencode(hostinfo)
        #data = pickle.dumps(hostinfo) #注释掉
        data = json.dumps(hostinfo) #添加一行
        req = urllib2.urlopen(req,data)
        print (req.read())
   


